package xyz.ibenben.zhongdian.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import xyz.ibenben.zhongdian.common.annotation.SystemControllerLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.system.entity.LeaveInfo;
import xyz.ibenben.zhongdian.system.entity.sys.SysUser;
import xyz.ibenben.zhongdian.system.form.LeaveInfoForm;
import xyz.ibenben.zhongdian.system.service.LeaveInfoService;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;

/**
 * 请假申请信息控制类
 * 提供了一些基本的服务，如初始化、获取请假申请信息列表等方法。
 * spring mvc思想 通过controller来调用service里的方法，
 * service里的方法再通过调用Dao来实现对数据的操作
 * 返回值统统是String类型的返回页面有统一的安排方便代码提取
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Slf4j
@Controller
@SessionAttributes("leaveInfoForm")
@RequestMapping("/leaveInfo")
public class LeaveInfoController extends BaseController {
    /**
     * 实体名称
     */
    private static final String ENTITYNAME = "leaveInfo";

    @Resource
    private LeaveInfoService leaveInfoService;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private TaskService taskService;

    /**
     * 初始化
     *
     * @param map           参数
     * @param leaveInfoForm 条件参数
     */
    @ModelAttribute
    public void init(Model map, @ModelAttribute LeaveInfoForm leaveInfoForm) {
        LeaveInfoForm newLeaveInfoForm = new LeaveInfoForm();
        if (leaveInfoForm != null) {
            newLeaveInfoForm = leaveInfoForm;
        }
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), newLeaveInfoForm);
    }

    /**
     * 获取请假申请信息列表
     *
     * @param map           参数
     * @param leaveInfoForm 条件参数
     * @return 页面
     */
    @RequestMapping(value = "/getAll")
    @SystemControllerLog(description = "获取请假申请信息列表")
    public String getAll(Model map, @ModelAttribute LeaveInfoForm leaveInfoForm) {
        log.info("getAll param LeaveInfoForm: {}", leaveInfoForm.toString());
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), leaveInfoForm);
        Page<LeaveInfo> page = new Page<>(leaveInfoForm.getPageIndex(), leaveInfoForm.getPageSize());
        IPage<LeaveInfo> result = leaveInfoService.findAll(page, leaveInfoForm);
        map.addAttribute(Constants.PI, result);
        return String.format(Constants.LISTPAGE, ENTITYNAME);
    }

    /**
     * 删除请假申请信息记录
     *
     * @param id 主键
     * @return 页面
     */
    @RequestMapping(value = "/delete")
    @SystemControllerLog(description = "删除请假申请信息记录")
    public String delete(@RequestParam("id") Long id, SessionStatus status) {
        leaveInfoService.removeById(id);
        status.setComplete();
        return String.format(Constants.REDIRECT, ENTITYNAME);
    }

    /**
     * 删除请假申请信息列表
     *
     * @param leaveInfoForm 条件参数
     * @return 页面
     */
    @RequestMapping("/deleteAll")
    @SystemControllerLog(description = "删除请假申请信息列表")
    public String deleteAll(@ModelAttribute LeaveInfoForm leaveInfoForm, SessionStatus status) {
        if (leaveInfoForm.getSelectIds() != null) {
            String[] ids = leaveInfoForm.getSelectIds().split(Constants.COMMA);
            for (String id : ids) {
                leaveInfoService.removeById(Long.parseLong(id));
            }
        }
        status.setComplete();
        return String.format(Constants.REDIRECT, ENTITYNAME);
    }

    /**
     * 打开请假申请信息添加页面
     *
     * @param map 参数
     * @return 页面
     */
    @GetMapping("/add")
    @SystemControllerLog(description = "打开请假申请信息添加页面")
    public String openAddPage(Model map, String key) {
        LeaveInfo leaveInfo = new LeaveInfo();
        leaveInfo.setActivitiKey(key);
        map.addAttribute(ENTITYNAME, leaveInfo);
        return String.format(Constants.ADDPAGE, ENTITYNAME);
    }

    /**
     * 保存请假申请信息添加记录
     *
     * @param leaveInfo     实体
     * @param bindingResult 校验
     * @return 页面
     */
    @PostMapping("/add")
    @SystemControllerLog(description = "保存请假申请信息添加记录")
    public String postAddMessage(@Valid @ModelAttribute(ENTITYNAME) LeaveInfo leaveInfo,
                                 BindingResult bindingResult, SessionStatus status) {
        if (!bindingResult.hasErrors()) {
            HashMap<String, Object> variables = new HashMap<>();
            if (StringUtils.isNotEmpty(leaveInfo.getName())) {
                variables.put("name", leaveInfo.getName());
            }
            if (null != leaveInfo.getType()) {
                variables.put("types", leaveInfo.getType());
            }
            if (StringUtils.isNotEmpty(leaveInfo.getReason())) {
                variables.put("reason", leaveInfo.getReason());
            }
            SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION);
            variables.put("user", sysUser.getUsername());
            //设置发起人
            Authentication.setAuthenticatedUserId(sysUser.getUsername());
            ProcessInstance instance = runtimeService
                    .startProcessInstanceByKey(leaveInfo.getActivitiKey(), variables);
            System.out.println("流程定义ID:" + instance.getProcessDefinitionId());
            System.out.println("流程实例ID:" + instance.getId());
            Task task = taskService.createTaskQuery().processInstanceId(instance.getId())
                    .processDefinitionId(instance.getProcessDefinitionId()).singleResult();
            task.setAssignee(sysUser.getUsername());
            taskService.complete(task.getId());
            leaveInfoService.save(leaveInfo);
            status.setComplete();
            return String.format(Constants.REDIRECT, ENTITYNAME);
        }
        return String.format(Constants.ADDPAGE, ENTITYNAME);
    }

    /**
     * 打开请假申请信息修改页面
     *
     * @param map 参数
     * @param id  主键
     * @return 页面
     */
    @GetMapping("/edit")
    @SystemControllerLog(description = "打开请假申请信息修改页面")
    public String openEditPage(Model map, @RequestParam("id") Long id) {
        map.addAttribute(ENTITYNAME, leaveInfoService.getById(id));
        return String.format(Constants.EDITPAGE, ENTITYNAME);
    }

    /**
     * 更新请假申请信息修改记录
     *
     * @param leaveInfo     实体
     * @param bindingResult 校验
     * @return 页面
     */
    @PostMapping("/edit")
    @SystemControllerLog(description = "更新请假申请信息修改记录")
    public String postEditMessage(@Valid @ModelAttribute(ENTITYNAME) LeaveInfo leaveInfo,
                                  BindingResult bindingResult, SessionStatus status) {
        if (!bindingResult.hasErrors()) {
            HashMap<String, Object> variables = new HashMap<>();
            if (StringUtils.isNotEmpty(leaveInfo.getName())) {
                variables.put("name", leaveInfo.getName());
            }
            if (null != leaveInfo.getType()) {
                variables.put("types", leaveInfo.getType());
            }
            if (StringUtils.isNotEmpty(leaveInfo.getReason())) {
                variables.put("reason", leaveInfo.getReason());
            }
            SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION);
            variables.put("user", sysUser.getUsername());
            //设置发起人
            Authentication.setAuthenticatedUserId(sysUser.getUsername());
            ProcessInstance instance = runtimeService
                    .startProcessInstanceByKey(leaveInfo.getActivitiKey(), variables);
            System.out.println("流程定义ID:" + instance.getProcessDefinitionId());
            System.out.println("流程实例ID:" + instance.getId());
            leaveInfoService.updateById(leaveInfo);
            Task task = taskService.createTaskQuery().processInstanceId(instance.getId())
                    .processDefinitionId(instance.getProcessDefinitionId()).singleResult();
            task.setAssignee(sysUser.getUsername());
            taskService.complete(task.getId());
            status.setComplete();
            return String.format(Constants.REDIRECT, ENTITYNAME);
        } else {
            return String.format(Constants.EDITPAGE, ENTITYNAME);
        }
    }

    /**
     * 浏览请假申请信息记录
     *
     * @param map           参数
     * @param id            主键
     * @param leaveInfoForm 条件参数
     * @return 页面
     */
    @GetMapping("/view")
    @SystemControllerLog(description = "浏览请假申请信息记录")
    public String openViewPage(Model map, @RequestParam("id") Long id,
                               @ModelAttribute LeaveInfoForm leaveInfoForm) {
        LeaveInfo info = leaveInfoService.getById(id);
        map.addAttribute(ENTITYNAME, info);
        return String.format(Constants.VIEWPAGE, ENTITYNAME);
    }

}

